package cn.richinfo.sparkdemo;

import java.util.Arrays;
import java.util.Iterator;
 


import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;

import scala.Tuple2;
 

public class WordCount1 {
	
	public static void main(String[] args) {
		/**
		 * 第一步.获取编程入口，sparkcontext对象
		 */
		SparkConf sf=new SparkConf();  
		sf.setAppName("WordCount1");
		sf.setMaster("local");
		JavaSparkContext jsc=new JavaSparkContext(sf);
		
		/**
		 * 第二步.通过编程入口加载数据，得到数据抽象（RDD）
		 */
		JavaRDD<String> lineRDD=jsc.textFile("file:///c:\\words.txt");
		
		/**
		 * 第三步.针对RDD进行业务处理
		 */
		JavaRDD<String> wordRDD=lineRDD.flatMap(new FlatMapFunction<String, String>() {
			//call方法只负责把一句话变成一堆单词的迭代器
			public Iterator<String> call(String lines) throws Exception { 
				String [] words=lines.split(" ");
				return Arrays.asList(words).iterator();
			}
		});
		
		JavaPairRDD<String,Integer> wordAndOne =wordRDD.mapToPair(new PairFunction<String, String, Integer>(){
			public Tuple2<String, Integer> call(String word) throws Exception { 
				return new Tuple2<String, Integer>(word, 1);
			}
		});
		
		//func==>（x:int，y:int）=》x+y
		//.reduceBykey((x,y)=>x+y)
		JavaPairRDD<String, Integer> wordCountsRDD=wordAndOne.reduceByKey(new Function2<Integer, Integer, Integer>() {
			
			public Integer call(Integer x, Integer y) throws Exception { 
				return x+y;
			}
		});
		
		/**
		 * 第四步.针对第三步的结果进行处理
		 */
		wordCountsRDD.foreach(new VoidFunction<Tuple2<String,Integer>>() {
			
			public void call(Tuple2<String, Integer> wordAndCount) throws Exception { 
				System.out.println(wordAndCount._1+"\t"+wordAndCount._2);
			}
		});
		/**
		 * 第五步.关闭sparkcontext
		 */
	}
	
	
	

}
